const app = getApp();
const date = new Date();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    coach: null,
    days: [],
    selectDay: '',
    dateStr: '', //格式化的时间yyyy-MM-dd
    appointmentText: '预约',
    appointmentTime: '',
    times: [{
        time: "08:00",
        canSelect: false,
        selected: false,
        showTime: "08:00"
      }, {
        time: "08:30",
        canSelect: false,
        selected: false,
        showTime: "08:30"
      }, {
        time: "09:00",
        canSelect: false,
        selected: false,
        showTime: "09:00"
      }, {
        time: "09:30",
        canSelect: false,
        selected: false,
        showTime: "09:30"
      },
      {
        time: "10:00",
        canSelect: false,
        selected: false,
        showTime: "10:00"
      }, {
        time: "10:30",
        canSelect: false,
        selected: false,
        showTime: "10:30"
      }, {
        time: "11:00",
        canSelect: false,
        selected: false,
        showTime: "11:00"
      }, {
        time: "11:30",
        canSelect: false,
        selected: false,
        showTime: "11:30"
      },
      {
        time: "12:00",
        canSelect: false,
        selected: false,
        showTime: "12:00"
      }, {
        time: "12:30",
        canSelect: false,
        selected: false,
        showTime: "12:30"
      }, {
        time: "13:00",
        canSelect: false,
        selected: false,
        showTime: "13:00"
      }, {
        time: "13:30",
        canSelect: false,
        selected: false,
        showTime: "13:30"
      },
      {
        time: "14:00",
        canSelect: false,
        selected: false,
        showTime: "14:00"
      }, {
        time: "14:30",
        canSelect: false,
        selected: false,
        showTime: "14:30"
      }, {
        time: "15:00",
        canSelect: false,
        selected: false,
        showTime: "15:00"
      }, {
        time: "15:30",
        canSelect: false,
        selected: false,
        showTime: "15:30"
      },
      {
        time: "16:00",
        canSelect: false,
        selected: false,
        showTime: "16:00"
      }, {
        time: "16:30",
        canSelect: false,
        selected: false,
        showTime: "16:30"
      }, {
        time: "17:00",
        canSelect: false,
        selected: false,
        showTime: "17:00"
      }, {
        time: "17:30",
        canSelect: false,
        selected: false,
        showTime: "17:30"
      },
      {
        time: "18:00",
        canSelect: false,
        selected: false,
        showTime: "18:00"
      }, {
        time: "18:30",
        canSelect: false,
        selected: false,
        showTime: "18:30"
      }, {
        time: "19:00",
        canSelect: false,
        selected: false,
        showTime: "19:00"
      }, {
        time: "19:30",
        canSelect: false,
        selected: false,
        showTime: "19:30"
      },
      {
        time: "20:00",
        canSelect: false,
        selected: false,
        showTime: "20:00"
      }, {
        time: "20:30",
        canSelect: false,
        selected: false,
        showTime: "20:30"
      }, {
        time: "21:00",
        canSelect: false,
        selected: false,
        showTime: "21:00"
      }, {
        time: "21:30",
        canSelect: false,
        selected: false,
        showTime: "21:30"
      },
      {
        time: "22:00",
        canSelect: false,
        selected: false,
        showTime: "22:00"
      }
    ]
  },
  getDate: function() {
    const year = date.getFullYear();
    let month = (date.getMonth() + 1).toString();
    if (month.length == 1) {
      month = '0' + '' + month;
    }
    let day = date.getDate().toString();
    if (day.length == 1) {
      day = '0' + '' + day;
    }
    return year + '-' + month + '-' + day;
  },

  getDataByDate: function(openId, appointmentDate) {
    const coach = this.data.coach;
    const that = this;
    wx.request({
      url: app.globalData.url + '/appointment/getCoachAppointment',
      data: {
        openId: coach.openId,
        appointmentDate: appointmentDate
      },
      method: 'POST',
      success: function(response) {
        if (response.data.success) {
          const appointmentContent = response.data.content;
          const alreadyAppointmentTime = [];
          if (appointmentContent && appointmentContent.length > 0) {
            appointmentContent.forEach(function(item) {
              alreadyAppointmentTime.push(item.appointmentTimeStart);
              const timeStart = item.appointmentTimeStart;
              const startArr = timeStart.split(':');
              const date = new Date('2010', '01', '01', startArr[0], startArr[1], '00');
              date.setMinutes(date.getMinutes() + 30);
              const next30 = (date.getHours().toString().length == 1 ? '0' + date.getHours().toString() : date.getHours().toString()) +
                ':' +
                (date.getMinutes().toString().length == 1 ? '0' + date.getMinutes().toString() : date.getMinutes().toString());
              alreadyAppointmentTime.push(next30);
              alreadyAppointmentTime.push(item.appointmentTimeEnd);
            });
          }
          coach.alreadyAppointmentTime = alreadyAppointmentTime;
          that.setData({
            coach: coach
          });
          that.initDaysAndTimes(coach);
        }
      }
    })
  },
  initDaysAndTimes: function(coach) {
    //初始化能选的时间
    const times = this.data.times;
    times.forEach(function(item) {
      item.showTime = item.time;
      item.selected = false;
      item.canSelect = false;
      if (coach.alreadyAppointmentTime && coach.alreadyAppointmentTime.indexOf(item.time) < 0) {
        item.canSelect = true;
      }
    });
    this.setData({
      times: times,
      appointmentText: '预约'
    });
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const coachString = wx.getStorageSync("coach");
    const coach = JSON.parse(coachString);
    const month = (date.getMonth() + 1).toString();
    //设置当前日期
    this.setData({
      coach: coach,
      selectDay: month + '.' + date.getDate()
    });
    //初始化日期，默认显示后7天
    const days = [];
    const nowDay = new Date();
    const arr = ['日', '一', '二', '三', '四', '五', '六'];
    for (let i = 0; i < 7; i++) {
      const day = nowDay.getMonth() + 1 + '.' + nowDay.getDate();
      const dayObject = {
        dayCh: "周" + "日一二三四五六".charAt(nowDay.getDay()),
        day: day
      };
      nowDay.setDate(nowDay.getDate() + 1);
      days.push(dayObject);
    }
    this.setData({
      days: days
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const coach = this.data.coach;
    const date = this.getDate();
    this.setData({
      dateStr: date
    });
    this.getDataByDate(coach.openId, date);
  },
  changeDate: function(e) {
    const index = e.currentTarget.dataset.index;
    const selectDay = this.data.days[index].day;
    this.setData({
      selectDay: selectDay
    });
    const arr = selectDay.split('.');
    const year = date.getFullYear();
    const month = arr[0].length == 1 ? '0' + arr[0] : arr[0];
    const day = arr[1].length == 1 ? '0' + arr[1] : arr[1];
    const dateStr = year + '-' + month + '-' + day;
    this.setData({
      dateStr: dateStr
    });
    this.refleshSelectTimes(dateStr);
  },
  refleshSelectTimes: function(dateStr) {
    const coach = this.data.coach;
    this.getDataByDate(coach.openId, dateStr);
  },
  selectAppointmentTime: function(e) {
    const index = e.currentTarget.dataset.index;
    const times = this.data.times;
    const selectedTime = times[index];
    if (selectedTime.canSelect) {
      const nextTime = times[index + 1];
      if (!nextTime.canSelect) {
        wx.showToast({
          title: '请选择正确的开始时间',
          icon: 'none'
        })
        return;
      }
      for (var i = 0; i < times.length; i++) {
        if (i === index) {
          selectedTime.selected = true;
          selectedTime.showTime = '从' + selectedTime.time;
          nextTime.selected = true;
          nextTime.showTime = '到' + times[i + 2].time;
        } else {
          if (i != index + 1) {
            times[i].selected = false;
            times[i].showTime = times[i].time;
          }
        }
      }
      this.setData({
        times: times,
        appointmentTime: selectedTime.time + '-' + times[index + 2].time,
        appointmentText: '预约(' + selectedTime.time + '-' + times[index + 2].time + ')'
      });
    }
  },
  selectError: function() {
    wx.showToast({
      title: '当前时间已经被预约',
      icon: 'none'
    });
  },

  toConfirmAppointment: function() {
    if (this.data.appointmentTime.length == 0) {
      wx.showToast({
        title: '请选择预约时间',
        icon: 'none'
      });
      return;
    }
    const coach = this.data.coach;
    const appointmentTime = this.data.appointmentTime;
    const appointmentTimeArr = appointmentTime.split('-');
    const userInfo = app.globalData.userInfo;
    const dateStr = this.data.dateStr;
    const url = app.globalData.url;
    //会员预约
    wx.showModal({
      title: '提示',
      content: '确定预约？',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: url + '/appointment/memberSave',
            data: {
              traineeOpenId: app.globalData.openId,
              traineeName: userInfo.nickName,
              traineeAvatarUrl: userInfo.avatarUrl,
              coachOpenId: coach.openId,
              coachAvatarUrl: coach.avatarUrl,
              coachName: coach.name,
              appointmentDate: dateStr,
              appointmentTimeStart: appointmentTimeArr[0],
              appointmentTimeEnd: appointmentTimeArr[1]
            },
            method: 'POST',
            success: function(response) {
              if (response.data.success) {
                wx.navigateBack({
                  delta: 2
                });
                wx.showToast({
                  title: '预约成功',
                  icon: 'none'
                })
              } else {
                wx.showToast({
                  title: '预约失败:' + response.data.message,
                  icon: 'none'
                })
              }
            }

          })
        } else if (res.cancel) {

        }
      }
    })
  }
})